package com.kx.smsplantform.strategy.impl;

import com.kx.smsplantform.strategy.Strategy;
import com.kx.smsplantform.utils.PushMessage2Queue;
import com.kx.smsplatform.common.constants.RabbitMQConstants;
import com.kx.smsplatform.common.constants.StrategyConstants;
import com.kx.smsplatform.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 路由处理策略
 *
 * @Author Sun
 * @Date 2021/7/2 11:36
 */
@Slf4j
@Service(value = "router")
public class RouterStrategy implements Strategy {
    @Autowired
    private PushMessage2Queue pushMessage2Queue;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("【策略模块-路由校验】 路由校验策略开始执行！！");
        //1. 判断submit中的gatewayID.
        int gatewayID = standardSubmit.getGatewayID();

        //2. 如果为0,记录日志,发送消息,返回false
        if(gatewayID == 0){
            log.info("【策略模块-路由策略】 路由策略失败, 没有指定的通道信息...");
            pushMessage2Queue.sendLogMessage(standardSubmit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            pushMessage2Queue.pushReportMessage(standardSubmit, StrategyConstants.STRATEGY_ERROR_ROUTER);
            return false;
        }

        //3. 直接发送消息到MQ
        // 避免404,先创建出这个队列
        String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + gatewayID;
        amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
        rabbitTemplate.convertAndSend(queueName,standardSubmit);
        log.info("【策略模块-路由校验】 路由校验策略执行结束！！");
        return true;
    }
}
